<template>
  <view class="content">
    <view class="app-title">
      <view class="app-title-item">
        <image class="back" src="/static/img/back.png" @click="back"></image>
        <text>监测曲线信息</text>
      </view>
    </view>

    <view class="content-curve">
      <!-- tab 切换 -->
      <u-tabs
        :list="tabs"
        :is-scroll="false"
        :current="tabActive"
        @change="tabsChange"
      ></u-tabs>
      <!-- 时间选择 -->
      <div class="select-section">
        <view class="equ-name">当前设备：{{ equName }}</view>
        <view class="select-item" @click="openTimeSelect('currentDate')">
          <view>日期</view>
          <view class="select-val">{{ currentDate || "请选择" }}</view>
        </view>
        <view class="select-item" @click="openTimeSelect('beginTime')">
          <view>{{ tabActive == 1 ? "时间" : "开始时间" }}</view>
          <view class="select-val">{{ beginTime || "请选择" }}</view>
        </view>
        <view
          v-if="tabActive != 1"
          class="select-item"
          @click="openTimeSelect('endTime')"
        >
          <view>结束时间</view>
          <view class="select-val">{{ endTime || "请选择" }}</view>
        </view>
        <!-- 时间 选择器 -->
        <u-picker
          v-model="timeShow"
          mode="time"
          :params="timeParams"
          @confirm="timeSelectConfirm"
        ></u-picker>

        <!-- 时间选择 10分钟间隔 -->
        <!-- <u-picker v-model="tenTimeShow" :columns="tenTimeColumns" @confirm="tenTimeConfirm"></u-picker> -->
        <u-select
          v-model="tenTimeShow"
          mode="mutil-column"
          :list="tenTimeColumns"
          @confirm="tenTimeConfirm"
        ></u-select>
        <u-select
          v-model="show"
          mode="single-column"
          :list="list"
          @confirm="confirm"
        ></u-select>
      </div>
      <!-- <view class="charts-section">
				<view class="charts-box">
					<qiun-data-charts type="line" :loadingType="0" :opts="opts" :chartData="chartData" />
				</view>
			</view> -->
      <view
        v-if="tabActive == 0 || tabActive == 1"
        class="curve-box"
        :class="{ analog: tabActive == 0, isSwitch: tabActive == 1 }"
      >
        <web-view
          v-if="wvSrc"
          :key="wvSrc"
          class="webViewClass"
          :class="{ analog: tabActive == 0, isSwitch: tabActive == 1 }"
          ref="webView"
          :src="wvSrc"
          :fullScreen="false"
          @message="getMessage"
        ></web-view>
      </view>
    </view>

    <u-mask :show="loading">
      <view class="loading-warp">
        <u-loading mode="circle" size="70"></u-loading>
      </view>
    </u-mask>
  </view>
</template>

<script>
import dayjs from "../../static/plugins/js/dayjs/dayjs.min.js";
import { mapState } from "vuex";
var wv; // 计划创建的webview
const info = uni.getSystemInfoSync();

export default {
  data() {
    return {
      pageType: "",
      equID: "",
      dbm: "",
      equTypeId: "",
      equName: "",
      // tab 切换
      tabs: [
        { id: 0, name: "日曲线", type: "analog" },
        { id: 0, name: "动作曲线", type: "curve" },
      ],
      tabActive: 0,
      currentItem: {},
      // 时间选择
      timeShow: false,
      timeType: "",
      timeParams: {},
      // 日期
      currentDate: "",
      // 开始时间 结束时间
      beginTime: "",
      endTime: "",
      // 10分钟间隔
      tenTimeShow: false,
      tenTimeColumns: [],
      // 时间
      dayData: [],
      dateList: [],
      show: false,
      list: [],
      // charts
      opts: {},
      chartData: {},
      loading: false,
      serverObj: null,
      ipVal: "",
      urlVal: "/iom5/monitorCurveApp",
      // webview
      wvSrc: "",
      currentWebview: null,
      topShowAnalog: 275,
      bottomVal: 0,
      topShow: 230,
      isMock: false,
      queryMockParams: {
        beginTime: "",
        endTime: "",
        equID: "",
        dbm: "",
      },
      queryParams: {},
    };
  },
  watch: {
    tabActive(val) {
      console.log(val, "tabActive");
      this.setWvStyle(wv, false);
      setTimeout(() => {
        this.setWvStyle(wv, true);
      }, 10);
    },
    timeShow(val) {
      console.log(val, "timeShow");
      this.setWvStyle(wv, !val);
    },
    tenTimeShow(val) {
      console.log(val, "tenTimeShow");
      this.setWvStyle(wv, !val);
    },
    show(val) {
      console.log(val, "show");
      this.setWvStyle(wv, !val);
    },
  },
  onLoad(options) {
    // 响应式数据、计算属性、方法、侦听器、props、slots 已设置完成
    console.log(
      "监测曲线信息::onload::",
      dayjs().format("YYYY-MM-DD HH:mm:ss"),
      options
    );

    this.pageType = options.type;

    this.equID = options.id;
    this.dbm = options.code;
    this.equTypeId = options.equTypeId;
    this.equName = options.equName;
    let tabList = this.tabs;
    if (this.equTypeId != 9) {
      this.tabs = tabList.splice(0, 1);
    } else {
      this.tabs = tabList;
    }
    this.tabs.length && this.tabsChange(0);
    // #ifdef APP-PLUS
    plus.screen.lockOrientation("portrait-primary");
    // #endif
    this.serverObj = this.$store.state.appServer;
    if (this.serverObj && this.serverObj.iom5Ip && this.serverObj.iom5Port) {
      this.ipVal = `http://${this.serverObj.iom5Ip}:${this.serverObj.iom5Port}`;
      this.wvSrc = `${this.ipVal}${this.urlVal}`;
      console.log("wvSrc:", this.wvSrc);
      setTimeout(() => {
        this.getWebView(); // 如果是页面初始化调用时，需要延时一下
      }, 500);
    } else {
      console.error("appServer配置报错");
    }
  },
  onShow() {
    // 页面每次出现在屏幕上都触发
  },
  onReady() {
    // 初次渲染完成，组件已挂载，dom可用
  },
  // onReachBottom
  methods: {
    getMessage(params) {
      // #ifdef APP-PLUS
      // let dataObj =
      //   (params &&
      //     params.detail &&
      //     params.detail.data &&
      //     Array.isArray(params.detail.data) &&
      //     params.detail.data[0]) ||
      //   {};
      // console.log("参数", dataObj);
      // if (dataObj.isFullView) {
      //   if (this.tabActive == 0) {
      //     this.setWvStyle(wv, true, 0);
      //     plus.screen.lockOrientation("landscape-primary");
      //   }
      // } else {
      //   if (this.tabActive == 0) {
      //     this.setWvStyle(wv, true, this.topShowAnalog);
      //     plus.screen.lockOrientation("portrait-primary");
      //   }
      // }
      // #endif
    },
    setWvStyle(wvObj, flag, topVal) {
      topVal =
        this.tabActive == 0
          ? this.topShowAnalog
          : this.tabActive == 1
          ? this.topShow
          : this.topShow;
      let topValFinal = flag ? topVal : info.windowHeight;
      // #ifdef APP-PLUS
      console.log(topVal);
      if (flag) {
        wvObj &&
          wvObj.setStyle({
            top: topValFinal,
            bottom: 0,
            // scalable:true,
          });
      } else {
        wvObj &&
          wvObj.setStyle({
            top: topValFinal,
            // scalable:true, scalable是否开启双指缩放
          });
      }
      // #endif
    },
    getWebView() {
      // #ifdef APP-PLUS
      var currentWebview = this.$scope.$getAppWebview(); // 获取当前页面的webview对象
      wv = currentWebview.children()[0];
      console.log(wv, "wv");
      // this.setParams();
      this.setWvStyle(wv, true);
      // if (this.tabActive == 0) {
      //   this.setWvStyle(wv, true, this.topShowAnalog);
      // } else if (this.tabActive == 1) {
      //   this.setWvStyle(wv, true, this.topShow);
      // }
      // #endif
    },
    setParams() {
      this.queryParams = {};
      if (this.tabActive == 0) {
        this.queryParams = {
          beginTime: this.currentDate + " " + this.beginTime,
          endTime: this.currentDate + " " + this.endTime,
          equID: this.equID,
          dbm: this.dbm,
        };
      } else if (this.tabActive == 1) {
        this.queryParams = {
          beginTime: this.beginTime,
          endTime: "",
          equID: this.equID,
          dbm: this.dbm,
        };
      }
      console.log("queryParams", this.queryParams);
      // #ifdef APP-PLUS
      if (wv) {
        let params = {
          appPageType: this.currentItem.type,
          searchInfo: {
            equName: this.equName,
          },
          csmDataType: 1,
          ...this.queryParams,
        };
        if (this.isMock) {
          // 调试参数
          if (this.tabActive == 0) {
            params = {
              ...params,
              beginTime: "2024-01-26 00:00:00",
              endTime: "2024-01-26 23:59:59",
              equID: "5178995740f24650876e8003444c24b2", // 201#J[103][CBZ][道岔#ZYJ7]
              dbm: "CBZ",
            };
          } else if (this.tabActive == 1) {
            // 调试参数
            params = {
              ...params,
              beginTime: "2023-12-28 09:14:56", // 2024-01-27 16:40:38
              endTime: "", // 2023-12-29 09:14:56
              equID: "5178995740f24650876e8003444c24b2", // 201#J[103][CBZ][道岔#ZYJ7]
              dbm: "CBZ",
            };
          }
        }
        console.log("setParams", params);
        console.log(JSON.stringify(params));
        if (params.beginTime) {
          wv.evalJS(`getWebviewParams(${JSON.stringify(params)})`);
        } else {
          console.error("缺少开始时间");
        }
      }
      // #endif
    },
    tabsChange(index) {
      console.log(index, 2323);
      this.currentDate = "";
      this.beginTime = "";
      this.endTime = "";
      this.chartData = {};
      this.tabActive = index;
      this.currentItem = this.tabs[index];
      if (index == 1) {
        this.queryDay();
      }
      if (index == 0) {
        // 初始化日曲线数据
        let now = dayjs();
        this.currentDate = now.format("YYYY-MM-DD");
        let roundedNow = this.roundDownTenMinutes(now);
        this.endTime = roundedNow.format("HH:mm") + ":00";
        this.beginTime =
          roundedNow
            .subtract(Number(this.appServer.day_curve_end_time) || 10, "minute")
            .format("HH:mm") + ":00";
        //等待h5页面创建完再访问
        setTimeout(() => {
          this.queryCharts();
        }, Number(this.appServer.monitor_curve_delay_time) || 3000);
      }
      // #ifdef APP-PLUS
      if (wv) {
        let params = {
          appPageType: "change",
        };
        wv.evalJS(`getWebviewParams(${JSON.stringify(params)})`);
      }
      // #endif
    },
    confirm(e) {
      if (this.timeType == "currentDate") {
        this.currentDate = e[0].value;
        this.queryTime();
      } else if (this.timeType == "beginTime") {
        this.beginTime = e[0].value;
      }
      this.queryCharts();
    },
    tenTimeConfirm(e) {
      if (this.tabActive == 0) {
        switch (this.timeType) {
          case "beginTime":
            this.beginTime = `${e[0].value}:${e[1].value}:00`;
            if (Number(e[1].value) == 50) {
              let hour = Number(e[0].value) + 1;
              hour = hour < 10 ? `0${hour}` : hour;
              this.endTime = `${hour}:00:00`;
            } else {
              this.endTime = `${e[0].value}:${Number(e[1].value) + 10}:00`;
            }
            break;
          case "endTime":
            this.endTime = `${e[0].value}:${e[1].value}:00`;
            break;
          default:
            break;
        }
      }

      this.queryCharts();
    },
    // 时间选择
    openTimeSelect(val) {
      this.timeType = val;

      if (this.timeType == "currentDate") {
        this.timeParams = {
          year: true,
          month: true,
          day: true,
        };
      }

      if (this.tabActive == 0 && this.timeType != "currentDate") {
        const hours = Array.from(
          {
            length: 24,
          },
          (v, i) => `${i < 10 ? "0" : ""}${i}`
        );

        let minutes = [];
        for (let minute = 0; minute < 60; minute += 10) {
          minutes.push(`${minute < 10 ? "0" : ""}${minute}`);
        }

        const hCols = hours.map((item) => {
          return {
            label: item,
            value: item,
          };
        });
        const mCols = minutes.map((item) => {
          return {
            label: item,
            value: item,
          };
        });

        this.tenTimeColumns = [hCols, mCols];

        this.tenTimeShow = true;
      } else if (this.tabActive == 1 && this.timeType == "currentDate") {
        this.list = this.dayData;
        this.show = true;
      } else if (this.tabActive == 1 && this.timeType == "beginTime") {
        this.list = this.dateList;
        this.show = true;
      } else {
        if (this.timeType == "beginTime" || this.timeType == "endTime") {
          this.timeParams = {
            hour: true,
            minute: true,
            second: true,
          };
        }
        this.timeShow = true;
      }
    },
    timeSelectConfirm(e) {
      switch (this.timeType) {
        case "currentDate":
          this.currentDate = `${e.year}-${e.month}-${e.day}`;
          break;
        case "beginTime":
          this.beginTime = `${e.hour}:${e.minute}:${e.second}`;
          break;
        case "endTime":
          this.endTime = `${e.hour}:${e.minute}:${e.second}`;
          break;
        default:
          break;
      }

      this.queryCharts();
    },
    queryDay() {
      const params = {
        beginTime:
          dayjs().subtract(1, "year").format("YYYY-MM-DD") + " 00:00:00",
        endTime: dayjs().format("YYYY-MM-DD") + " 23:59:59",
        equID: this.equID,
        dbm: this.dbm,
      };

      let serverObj = this.$store.state.appServer;
      let baseUrl = `http://${serverObj.csIp}:${serverObj.csPort}`;
      this.fetch(
        "get",
        baseUrl + "/t5/faultanalysis/getE0SupportOneYearCurveTime",
        params,
        false
      ).then((res) => {
        const { data } = res;
        if (data && data.length) {
          this.dayData = data.map((item) => {
            return {
              label: item,
              value: item,
            };
          });
          // 自动获取最近一次动作曲线日期
          this.timeType = "currentDate";
          this.confirm([this.findLatestItem(this.dayData)]);
        }
      });
    },
    queryTime() {
      const params = {
        beginTime: this.currentDate + " 00:00:00",
        endTime: this.currentDate + " 23:59:59",
        equID: this.equID,
        dbm: this.dbm,
      };

      let serverObj = this.$store.state.appServer;
      let baseUrl = `http://${serverObj.csIp}:${serverObj.csPort}`;
      this.fetch(
        "get",
        baseUrl + "/t5/faultanalysis/getE0SupportCurveTime",
        params,
        false
      ).then((res) => {
        const { data } = res;
        if (data && data.length) {
          this.dateList = data.map((item) => {
            return {
              label: item,
              value: item,
            };
          });
          // 自动获取最近一次动作曲线时间并查询数据
          this.timeType = "beginTime";
          this.confirm([this.findLatestItem(this.dateList)]);
          this.queryCharts();
        }
      });
    },
    // 获取曲线图数据
    queryCharts() {
      if (
        this.tabActive == 0 &&
        (!this.currentDate || !this.beginTime || !this.endTime)
      )
        return;
      if (this.tabActive == 1 && (!this.currentDate || !this.beginTime)) return;
      this.setParams();
      return;
      const url =
        this.tabActive == 1
          ? "/t5/faultanalysis/getE0SupportCurveData"
          : "/t5/mobilemonitoringdata/getDevCjxPeriodData";

      let params = {};

      if (this.tabActive == 0) {
        params = {
          beginTime: this.currentDate + " " + this.beginTime,
          endTime: this.currentDate + " " + this.endTime,
          equID: this.equID,
          dbm: this.dbm,
        };
      }
      if (this.tabActive == 1) {
        params = {
          beginTime: this.beginTime,
          endTime: "",
          equID: this.equID,
          dbm: this.dbm,
        };
      }

      this.loading = true;

      let serverObj = this.$store.state.appServer;
      let baseUrl = `http://${serverObj.csIp}:${serverObj.csPort}`;
      this.fetch("get", baseUrl + url, params, false)
        .then((res) => {
          const { code, status_code, data } = res;
          if (code == 200 && status_code == 200) {
            if (
              this.tabActive == 0 &&
              data.analogRawDataAnalyseResultList &&
              data.analogRawDataAnalyseResultList.length
            ) {
              const chartData = data.analogRawDataAnalyseResultList;
              this.renderCharts(chartData);
            }
            if (this.tabActive == 1 && data.dcqxRawDataAnalyseResult) {
              const chartData =
                data.dcqxRawDataAnalyseResult.currentCurveSetList;
              this.renderCharts(chartData);
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    renderCharts(chartDatas) {
      if (chartDatas.length > 1 && this.tabActive == 1) {
        console.log(chartDatas[0].dataContentList.length);
        this.opts = {
          dataLabel: false,
          padding: [15, 12, 0, 0],
          xAxis: {
            // labelCount: chartDatas[0].dataContentList.length,
            boundaryGap: "justify",
          },
          yAxis: {
            gridType: "dash",
          },
          extra: {
            line: {
              type: "curve",
            },
          },
        };

        const arr = [];
        chartDatas.forEach((item, index) => {
          arr.push({
            name: item.cjxTypeName + (index + 1),
            data: item.dataContentList
              .flat()
              .map((item) => (item % 1 === 0 ? item : Number(item.toFixed(2)))),
          });
        });
        console.log(arr);
        console.log(
          Array(chartDatas[0].dataContentList.length)
            .fill()
            .map((_, index) => index.toString())
        );
        let res = {
          categories: Array(chartDatas[0].dataContentList.length)
            .fill()
            .map((_, index) => index.toString()),
          series: arr,
        };

        this.chartData = JSON.parse(JSON.stringify(res));
      } else if (this.tabActive == 0) {
        this.opts = {
          dataLabel: false,
          padding: [15, 12, 0, 0],
          xAxis: {
            labelCount: 6,
            boundaryGap: "center",
          },
          yAxis: {
            gridType: "dash",
          },
          extra: {
            line: {
              type: "curve",
            },
          },
        };

        let res = {
          categories: chartDatas[0].dataContentList.map((item) =>
            dayjs(item.collectTime).format("HH:mm")
          ),
          series: [
            {
              name: chartDatas[0].cjxName,
              data: chartDatas[0].dataContentList.map((item) =>
                item.collectValue % 1 === 0
                  ? item.collectValue
                  : Number(item.collectValue.toFixed(3))
              ),
            },
          ],
        };
        this.chartData = JSON.parse(JSON.stringify(res));
      }
    },
    // 返回
    back() {
      uni.navigateBack();
    },
    // 转换需要比对的时间对象
    parseDate(dateString) {
      let parts = dateString.split(/[- :T]/);
      return new Date(
        Date.UTC(
          parts[0],
          parts[1] - 1,
          parts[2],
          parts[3] || 0,
          parts[4] || 0,
          parts[5] || 0
        )
      );
    },
    // 获取日期数组列表中最近的日期
    findLatestItem(items) {
      let latestItem = null;
      let latestDate = new Date(0);
      for (const item of items) {
        let itemDate = this.parseDate(item.value);
        if (!isNaN(itemDate.getTime()) && itemDate > latestDate) {
          latestDate = itemDate;
          latestItem = item;
        }
      }
      return latestItem;
    },
    // 向下取整最近的10分钟
    roundDownTenMinutes(currentDayjsObj) {
      let minutes = currentDayjsObj.minute();
      let remainder = minutes % 10;
      if (remainder !== 0) {
        return currentDayjsObj.subtract(remainder, "minute");
      }
      return currentDayjsObj;
    },
  },
  computed: {
    ...mapState(["appServer"]),
  },
};
</script>

<style scoped lang="less">
.content {
  width: 100%;
  height: 100vh;
  background: #fff;
  position: fixed;

  display: flex;
  flex-direction: column;

  .app-title {
    text-align: center;
    height: 65px;
    .app-title-item {
      position: relative;
    }

    .back {
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
    }
  }

  .content-curve {
    height: 0;
    flex: 1;
    flex-basis: 0;

    display: flex;
    flex-direction: column;
    .select-section {
      padding: 5px 0;
      background: #f3f3f3;
      .equ-name {
        padding: 5px;
        height: 30px;
      }
    }

    .select-item {
      height: 44px;
      padding: 12px 18px;
      background: #fff;

      display: flex;
      align-items: center;

      & + .select-item {
        border-top: 1px solid #eee;
      }

      .select-val {
        width: 0;
        flex: 1;
        flex-basis: 0;

        text-align: right;
      }
    }
  }
}

.charts-box {
  width: 100%;
  height: 300px;
}

.loading-warp {
  height: 98vh;

  display: flex;
  align-items: center;
  justify-content: center;
}
.curve-box {
  width: 100%;
  &.analog {
    height: calc(100vh - 275px);
    bottom: 0px;
  }
  &.isSwitch {
    height: calc(100vh - 230px);
    bottom: 0px;
  }
  .webViewClass {
    // height: 100%;
    &.analog {
      height: calc(100vh - 275px);
      top: 275px;
      bottom: 0px;
    }
    &.isSwitch {
      height: calc(100vh - 230px);
      top: 230px;
      bottom: 0px;
    }
  }
}
</style>
